import { ref, computed, watchEffect, onMounted } from 'vue'
import { useTheme } from './useTheme'

/**
 * 滚动条配置接口
 */
export interface ScrollbarConfig {
  width: number // 滚动条宽度（px）
  height: number // 滚动条滑块最小高度（px）
  trackColor: string // 轨道颜色
  thumbColor: string // 滑块颜色
  thumbHoverColor: string // 滑块悬停颜色
  borderRadius: number // 圆角大小（px）
}

/**
 * 预设的滚动条配置主题
 */
const SCROLLBAR_PRESETS = {
  default: {
    light: {
      width: 8,
      height: 20,
      trackColor: '#f8fafc',
      thumbColor: '#22c55e',
      thumbHoverColor: '#16a34a',
      borderRadius: 4
    },
    dark: {
      width: 8,
      height: 20,
      trackColor: '#1a1a1a',
      thumbColor: '#00ff88',
      thumbHoverColor: '#00cc6a',
      borderRadius: 4
    }
  },
  thin: {
    light: {
      width: 4,
      height: 16,
      trackColor: '#f1f5f9',
      thumbColor: '#3b82f6',
      thumbHoverColor: '#2563eb',
      borderRadius: 2
    },
    dark: {
      width: 4,
      height: 16,
      trackColor: '#0f172a',
      thumbColor: '#60a5fa',
      thumbHoverColor: '#3b82f6',
      borderRadius: 2
    }
  },
  thick: {
    light: {
      width: 12,
      height: 24,
      trackColor: '#e2e8f0',
      thumbColor: '#059669',
      thumbHoverColor: '#047857',
      borderRadius: 6
    },
    dark: {
      width: 12,
      height: 24,
      trackColor: '#334155',
      thumbColor: '#10b981',
      thumbHoverColor: '#059669',
      borderRadius: 6
    }
  },
  minimal: {
    light: {
      width: 2,
      height: 12,
      trackColor: 'transparent',
      thumbColor: '#94a3b8',
      thumbHoverColor: '#64748b',
      borderRadius: 1
    },
    dark: {
      width: 2,
      height: 12,
      trackColor: 'transparent',
      thumbColor: '#475569',
      thumbHoverColor: '#64748b',
      borderRadius: 1
    }
  }
} as const

type ScrollbarPreset = keyof typeof SCROLLBAR_PRESETS

/**
 * 滚动条配置管理Composable
 */
export function useScrollbarConfig() {
  const { isDark } = useTheme()
  
  // 当前预设名称
  const currentPreset = ref<ScrollbarPreset>('default')
  
  // 自定义配置
  const customConfig = ref<Partial<ScrollbarConfig>>({})
  
  // 是否使用自定义配置
  const useCustom = ref(false)

  /**
   * 获取当前主题下的预设配置
   */
  const getPresetConfig = (preset: ScrollbarPreset): ScrollbarConfig => {
    const themeKey = isDark.value ? 'dark' : 'light'
    return SCROLLBAR_PRESETS[preset][themeKey]
  }

  /**
   * 当前生效的滚动条配置
   */
  const currentConfig = computed<ScrollbarConfig>(() => {
    const baseConfig = getPresetConfig(currentPreset.value)
    
    if (useCustom.value) {
      return { ...baseConfig, ...customConfig.value }
    }
    
    return baseConfig
  })

  /**
   * 应用滚动条样式到DOM
   */
  const applyScrollbarStyles = () => {
    const config = currentConfig.value
    
    // 创建或更新样式标签
    let styleElement = document.getElementById('scrollbar-config-styles')
    if (!styleElement) {
      styleElement = document.createElement('style')
      styleElement.id = 'scrollbar-config-styles'
      document.head.appendChild(styleElement)
    }
    
    const styles = `
      ::-webkit-scrollbar {
        width: ${config.width}px;
      }
      
      ::-webkit-scrollbar-track {
        background: ${config.trackColor};
      }
      
      ::-webkit-scrollbar-thumb {
        background: ${config.thumbColor};
        border-radius: ${config.borderRadius}px;
        transition: background-color 0.2s ease;
      }
      
      ::-webkit-scrollbar-thumb:vertical {
        min-height: ${config.height}px;
      }
      
      ::-webkit-scrollbar-thumb:horizontal {
        min-width: ${config.height}px;
      }
      
      ::-webkit-scrollbar-thumb:hover {
        background: ${config.thumbHoverColor};
      }
      
      /* Firefox 滚动条样式 */
      * {
        scrollbar-width: ${config.width <= 4 ? 'thin' : config.width >= 12 ? 'auto' : 'auto'};
        scrollbar-color: ${config.thumbColor} ${config.trackColor};
      }
    `
    
    styleElement.textContent = styles
  }

  /**
   * 设置预设主题
   */
  const setPreset = (preset: ScrollbarPreset) => {
    currentPreset.value = preset
    useCustom.value = false
    localStorage.setItem('scrollbar-preset', preset)
    localStorage.removeItem('scrollbar-custom-config')
    localStorage.removeItem('scrollbar-use-custom')
  }

  /**
   * 设置自定义配置
   */
  const setCustomConfig = (config: Partial<ScrollbarConfig>) => {
    customConfig.value = { ...customConfig.value, ...config }
    useCustom.value = true
    localStorage.setItem('scrollbar-custom-config', JSON.stringify(customConfig.value))
    localStorage.setItem('scrollbar-use-custom', 'true')
  }

  /**
   * 重置为默认配置
   */
  const resetToDefault = () => {
    setPreset('default')
  }

  /**
   * 获取所有可用的预设
   */
  const getAvailablePresets = () => {
    return Object.keys(SCROLLBAR_PRESETS) as ScrollbarPreset[]
  }

  /**
   * 从localStorage加载保存的配置
   */
  const loadSavedConfig = () => {
    const savedPreset = localStorage.getItem('scrollbar-preset') as ScrollbarPreset
    const savedCustomConfig = localStorage.getItem('scrollbar-custom-config')
    const savedUseCustom = localStorage.getItem('scrollbar-use-custom')
    
    if (savedPreset && savedPreset in SCROLLBAR_PRESETS) {
      currentPreset.value = savedPreset
    }
    
    if (savedCustomConfig) {
      try {
        customConfig.value = JSON.parse(savedCustomConfig)
      } catch (e) {
        console.warn('Failed to parse saved scrollbar config:', e)
      }
    }
    
    if (savedUseCustom === 'true') {
      useCustom.value = true
    }
  }

  // 监听配置变化并应用样式
  watchEffect(() => {
    applyScrollbarStyles()
  })

  // 组件挂载时加载保存的配置
  onMounted(() => {
    loadSavedConfig()
    applyScrollbarStyles()
  })

  return {
    // 状态
    currentPreset,
    customConfig,
    useCustom,
    currentConfig,
    
    // 方法
    setPreset,
    setCustomConfig,
    resetToDefault,
    getAvailablePresets,
    getPresetConfig,
    
    // 预设常量
    SCROLLBAR_PRESETS
  }
}

// 导出类型
export type { ScrollbarPreset }
export type UseScrollbarConfigReturn = ReturnType<typeof useScrollbarConfig>